package com.wnhoo.smartfishtank.fishtank;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wnhoo.smartfishtank.R;
import com.wnhoo.smartfishtank.api.LM_TimingAPI;
import com.wnhoo.smartfishtank.api.data.DataTiming;
import com.wnhoo.smartfishtank.api.data.LM_DataSend;
import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.base.BaseActivity;
import com.wnhoo.smartfishtank.contants.adapter.AdapterLightTiming;
import com.wnhoo.smartfishtank.ui.UISwitchButton;
import com.wnhoo.smartfishtank.util.CustomDialog;
import com.wnhoo.smartfishtank.util.MyLog;
import com.wnhoo.smartfishtank.util.ShowToastUtil;

import java.util.ArrayList;
import java.util.List;


public class Light_Timing_ListActivity extends BaseActivity implements BaseActivity.InitHeaderListener,
        AdapterLightTiming.OnItemTimingListener {

    private ListView light_timing_list;
    private TextView light_timing_time_tv, light_timing_color;
    private UISwitchButton light_timing_uibutton;
    private List<DataTiming> list_timing;
    private AdapterLightTiming adapterLightTiming;
    private SharedPreferences share;
    private int timingSwitch;//当前定时滑动按钮的位置
    private static final String tag = "Light_Timing_ListActivity";
    private CustomDialog dialog;

    public CustomDialog getDialog() {
        return dialog;
    }

    public void setDialog(CustomDialog dialog) {
        this.dialog = dialog;
    }

    public List<DataTiming> getList_timing() {
        if (list_timing == null) {
            list_timing = new ArrayList<>();
        }
        return list_timing;
    }

    private final String share_key_timng = "timing_list_json";
    public static Light_Timing_ListActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light__timing);
        setOnInitListener(this);
        initView();
        initData();
    }

    private void initData() {
//        share = getSharedPreferences(KContants.SPF_PLUG_CONFIG, MODE_PRIVATE);
    }

    @Override
    public void initView() {
        super.initView();
        instance = this;

        light_timing_list = (ListView) findViewById(R.id.light_timing_list);
        light_timing_time_tv = (TextView) findViewById(R.id.light_timing_time_tv);
        light_timing_color = (TextView) findViewById(R.id.light_timing_color);
        light_timing_uibutton = (UISwitchButton) findViewById(R.id.light_timing_uibutton);

        timingSwitch = ColorActivity.instance.getTimingSwitch();
        Log.i(TAG,"ColorActivity.instance"+timingSwitch);
        setShowTimingList();

        adapterLightTiming = new AdapterLightTiming(list_timing, getApplication());
        adapterLightTiming.setOnItemTimingListener(this);
        light_timing_list.setAdapter(adapterLightTiming);
    }

    @Override
    protected void onPause() {
        super.onPause();
        timingSwitch = 0;
        list_timing = null;
    }

    /**
     * 设置显示的默认的列表还是自定义的列表
     */
    private void setShowTimingList() {
        if (timingSwitch == 2) {
            list_timing = ColorActivity.instance.list_timing_default;
        } else {
            list_timing = ColorActivity.instance.list_timing;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        timingSwitch = ColorActivity.instance.getTimingSwitch();
        setShowTimingList();
        adapterLightTiming.notifyDataSetChanged();
    }

    @Override
    public void OnSetTitle(TextView t) {
        t.setTextColor(this.getResources().getColor(R.color.ther_text_color));
        t.setText(getStringXml(R.string.timing_list));
    }

    @Override
    public void OnSetLeftView(Button btn) {
        btn.setVisibility(View.VISIBLE);
    }

    @Override
    public void OnSetRightView(Button btn) {

    }

    @Override
    public void OnSetLeftOnclick(View view) {
    }

    @Override
    public void OnSetRightOnclick(View view) {

    }

    @Override
    public void onSetbackground(View view) {
        view.setBackgroundResource(R.drawable.solid_shadow);
    }

    @Override
    public boolean ItemOnclick(final int rowPosition, View view) {
//        Intent intent = new Intent(this, Light_Timing_ItemActivity.class);
//        intent.putExtra("position", position);
//        startActivity(intent);
        if(timingSwitch == 2){
            ShowToastUtil.show(getApplication(),getStringXml(R.string.defult));
            return false;
        }
        dialog = new CustomDialog(Light_Timing_ListActivity.this,R.layout.color_select);
        dialog.setOnClickItem(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String color = null;
                if(position<10){
                    color = String.valueOf("0" + position);
                }else{
//                    color = String.valueOf(position);
                    color = "0" + Integer.toHexString(position);
                }
//                Log.i("XXXXX", "----- Chose Fix Color .");
//                Toast.makeText(Light_Timing_ListActivity.this, "Chose Fix Color", Toast.LENGTH_SHORT).show();
                // Chimo
                list_timing.get(rowPosition).setColor(color);
                adapterLightTiming.notifyDataSetChanged();
                sendToClound();
                dialog.dismiss();
            }
        });
        dialog.show();
        return false;
    }

    @Override
    public void onUISwitchChange(int position, CompoundButton compoundButton, boolean b) {
        if (b) {
            list_timing.get(position).setPerion_value("ff");
            updateTiming(list_timing,true);
        } else {
            list_timing.get(position).setPerion_value("7f");
            updateTiming(list_timing, true);
        }
    }

    /**
     * 向服务器发送定时数据
     */
    class AsyncTaskSend extends AsyncTask<String, Integer, LM_DataSend> {//继承AsyncTask

        @Override
        protected LM_DataSend doInBackground(String... params) {//处理后台执行的任务，在后台线程执行
            LM_DataSend data = null;
            try {
                data = LM_TimingAPI.sendTimingList(list_timing, LMAPP.dataPlug.getId(), LMAPP.token_default, 1);
//                Log.d(TAG, "deviceID -->" + LMAPP.dataPlug.getId());
            } catch (Exception e) {
                MyLog.exception(e);
            }

            MyLog.d(tag, "result data -->" + data);
            return data;
        }

        protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用，在ui线程执行
        }

        protected void onPostExecute(LM_DataSend data) {//后台任务执行完之后被调用，在ui线程执行
            if (data != null && !data.isResult()) {
                ShowToastUtil.showShort(getApplication(),getStringXml(R.string.operation_failure));

            } else {
//                ShowToastUtil.showShort(getApplication(), "");
                ColorActivity.instance.saveToSPF();
//                startActivity(new Intent(Light_Timing_ListActivity.instance, Light_Timing_ListActivity.class));
            }
        }

        protected void onPreExecute() {//在 doInBackground(Params...)之前被调用，在ui线程执行
        }

        protected void onCancelled() {//在ui线程执行
        }
    }

    /**
     * 列表要设置8组定时，如果没有设置就显示为空
     */
    public void setTiming_List() {
        if (list_timing == null) {
            list_timing = new ArrayList<>();
        }
        for (int i = list_timing.size(); i < 8; i++) {
            DataTiming dataTiming = new DataTiming();
            dataTiming.setSend_timing(false);//未设置过这个定时
            list_timing.add(dataTiming);
        }
    }

    public void saveToSPF() {
        MyLog.d(TAG, "saveToSPF--------------------------------------------");
        Gson gson = new Gson();
        SharedPreferences.Editor editor = share.edit();
        editor.putString(share_key_timng, gson.toJson(list_timing));
        editor.apply();
    }

    /**
     * 将定时数据发送到服务器
     */
    public void sendToClound() {
//        Toast.makeText(Light_Timing_ListActivity.this, "sendToClound->", Toast.LENGTH_SHORT).show();
        MyLog.e(TAG, "sendToClound->");
        AsyncTaskSend asy = new AsyncTaskSend();
        asy.execute("");
    }

    /**
     * listview更新timing
     *
     * @param list
     */
    public void updateTiming(List<DataTiming> list, boolean isSendToClound) {
        MyLog.d(TAG, "updateTiming*********************************");
//        if(list!=null){
//            list_timing.clear();
//            for(DataTiming data:list){
//                list_timing.add(data);
//            }
//        }
//        adapterLightTiming.notifyDataSetChanged();
        if (isSendToClound) {
            MyLog.d(TAG, "updateTiming 发到云端");
            sendToClound();
        } else {
            MyLog.d(TAG, "updateTiming 不发到云端");
        }
    }
}
